package com.example.park;

import org.json.JSONException;
import org.json.JSONObject;

import java.nio.charset.StandardCharsets;


public class Protocol {

    public static String Encode(String jsonString) {
        int len = jsonString.getBytes(StandardCharsets.UTF_8).length;
        String fullMessage = len + "\n" + jsonString + "\n";
        return fullMessage;
    }

    public static String Decode(String buffer, StringBuilder remaining) {
        int sepIndex = buffer.indexOf("\n");
        if (sepIndex == -1) return null;

        String lenStr = buffer.substring(0, sepIndex);
        int len;
        try {
            len = Integer.parseInt(lenStr);
        } catch (NumberFormatException e) {
            return null;
        }

        int totalLen = sepIndex + 1 + len + 1;
        if (buffer.length() < totalLen) return null;

        if (buffer.charAt(sepIndex + 1 + len) != '\n') return null;

        String jsonStr = buffer.substring(sepIndex + 1, sepIndex + 1 + len);
        if (remaining != null) {
            remaining.setLength(0);
            remaining.append(buffer.substring(totalLen));
        }
        return jsonStr;
    }
}